/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Canvas2ImagePlugin.h"
#include "FileCache.h"

REGISTER_PLUGIN_CLASS(Canvas2ImagePlugin)
bool Canvas2ImagePlugin::execute(const string&  action, cJSON* args, CallbackContext cbc)
{
    if(action == "onArKTsResult") {
        return onArKTsResult(args);
    }
    
    if(action == "saveImageDataToLibrary") {
        m_cbc = cbc;
        string base64 = cJSON_GetArrayItem(args, 0)->valuestring;
        if(base64.empty()) {
            cbc.error("Missing base64 string");
            return true;
        }
        
        int nSize = 0;
        const char* decodeString = CBase64::decode(base64.c_str(), nSize);
        
        if(nSize <= 0) {
            cbc.error("Missing base64 string");
            return true;
        }
        string strFileName = FileCache::generalFileName()+FileCache::getImageType(base64);
        string strFilePath = Application::g_databaseDir.substr(0, Application::g_databaseDir.find("database")-1)+"/base/temp/" + strFileName;
        if(!FileCache::writeFile(strFilePath, decodeString, nSize)) {
            cbc.error("Missing base64 string");
            return true;
        }
        
        return executeArkTs("./AlertDialog/AlertDialog/SaveButtonImg", 0, strFilePath.c_str(), "Canvas2ImagePlugin", cbc);
    }
    return true;
}
bool Canvas2ImagePlugin::onArKTsResult(cJSON* args)
{
    string content = cJSON_GetObjectItem(args, "content")->valuestring;
    cJSON* json = cJSON_GetObjectItem(args, "result");
    if(json != NULL && json->type == cJSON_Array) {
        int count = cJSON_GetArraySize(json);
        if(count > 0) {
            string result = cJSON_GetArrayItem(json, 0)->valuestring;
            m_cbc.success(result);
        } else {
            m_cbc.error(content);
        }
    }
    return true;    
}
